#-*-coding:utf-8-*-
import os
import sys
import shutil as  hou
# import hou
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *

class Name(QWidget):
    name_Signal=Signal(str)
    def __init__(self):
        super(Name, self).__init__()
        self.main_layout=QVBoxLayout()
        self.name_label=QLabel('New Name:')
        self.name_edit=QLineEdit()
        self.name_btn=QPushButton('OK')
        self.name_btn.clicked.connect(self._set_name)
        self.main_layout.addWidget(self.name_label)
        self.main_layout.addWidget(self.name_edit)
        self.main_layout.addWidget(self.name_btn)
        self.setLayout(self.main_layout)

    def _set_name(self):
        name=self.name_edit.text()
        if name:
            self.name_Signal.emit(name)
            self.close()

class GlobalControl(QWidget):
    def __init__(self,project_path):
        super(GlobalControl, self).__init__()
        #path : \\xxx\xx\projects.info
        #self.CONFIG_PATH=path#os.path.join(os.path.dirname(os.path.dirname(__file__)) ,'events','config')
        self.project_root_path=project_path
        self.Project_Info_Path=os.path.join(self.project_root_path,'projects.info')
        print('Project_Info_Path:',self.Project_Info_Path)
        self.config_data=self.init_data(self.Project_Info_Path)  #{'GJWD': ['古剑网大', '#805952', 25, '2048x1152'],'XMM': ['致我们甜甜的小美满_BJ', '#92cddc', 25, '2048x1152']}

        self.current_project=''  #current selected project
        self.current_eps=''      #current selected eps
        self.current_shot=''     #current selected shot
        self.current_pipeline='' #current selected pipeline
        self.current_shot_info={}#current shot info

        self.setWindowTitle('GlobalControl')
        self.main_layout=QVBoxLayout()
        self.main_layout.setSpacing(15)
        self.project_layout=QHBoxLayout()
        self.project_label=QLabel('Project:')
        self.choose_project_btn=QPushButton('- -')
        # self.choose_project_btn.clicked.connect(self._open_project_window)
        self.project_comb=QComboBox()
        self.init_project_comb(self.config_data)
        self.project_comb.currentTextChanged.connect(self._project_changed)
        self.project_layout.addWidget(self.project_label)
        self.project_layout.addWidget(self.project_comb)
        self.eps_layout=QHBoxLayout()
        self.eps_label=QLabel('Eps:')
        self.eps_comb=QComboBox()
        self.init_eps_comb()
        self.eps_comb.currentTextChanged.connect(self._eps_changed)
        self.eps_layout.addWidget(self.eps_label)
        self.eps_layout.addWidget(self.eps_comb)
        self.shot_layout=QHBoxLayout()
        self.shot_label=QLabel('Shot:')
        self.shot_comb=QComboBox()
        self.shot_comb.currentTextChanged.connect(self._shot_changed)
        self.shot_layout.addWidget(self.shot_label)
        self.shot_layout.addWidget(self.shot_comb)
        self.pipeline_layout=QHBoxLayout()
        self.pipeline_label=QLabel('任务阶段:')
        self.pipeline_comb=QComboBox()
        self.pipeline_comb.currentTextChanged.connect(self._pipeline_changed)
        self.pipeline_layout.addWidget(self.pipeline_label)
        self.pipeline_layout.addWidget(self.pipeline_comb)
        self.save_layout=QHBoxLayout()
        self.save_layout.setContentsMargins(10,20,10,10)
        self.save_layout.setSpacing(25)
        self.save_btn=QPushButton('Save File')
        self.save_btn.clicked.connect(self._save_file)
        self.version_save_btn=QPushButton('Save File (update version)')
        self.version_save_btn.clicked.connect(self._save_update)
        self.save_layout.addWidget(self.save_btn)
        self.save_layout.addWidget(self.version_save_btn)


        self.set_layout=QHBoxLayout()
        self.set_frame_btn=QPushButton('Set Frame')
        self.set_frame_btn.clicked.connect(self._set_frame)
        self.set_fps_btn=QPushButton('Set FPS')
        self.set_fps_btn.clicked.connect(self._set_fps)
        self.set_layout.addWidget(self.set_frame_btn)
        self.set_layout.addWidget(self.set_fps_btn)

        self.import_layout=QVBoxLayout()
        self.import_cam_btn=QPushButton('Import Camera')
        self.import_ani_btn=QPushButton('Import Animation')

        self.text_layout=QVBoxLayout()
        self.text_label=QLabel('Shot Info:')
        self.text_brower=QTextBrowser()
        self.text_layout.addWidget(self.text_label)
        self.text_layout.addWidget(self.text_brower)

        self.main_layout.addLayout(self.project_layout)
        self.main_layout.addLayout(self.eps_layout)
        self.main_layout.addLayout(self.shot_layout)
        self.main_layout.addLayout(self.pipeline_layout)
        self.main_layout.addLayout(self.save_layout)
        self.main_layout.addLayout(self.set_layout)
        self.main_layout.addLayout(self.import_layout)
        self.main_layout.addLayout(self.text_layout)

        self.setLayout(self.main_layout)


    def init_config(self,config_path):
        config_data={}
        if os.path.exists(config_path):
            with open(config_path,'r') as r: #,encoding='utf8'
                config_data=eval(r.read())
        print('config_data:',config_data)
        return config_data

    def init_data(self,path):
        data={}
        if os.path.exists(path):
            with open(path,'r',encoding='utf8') as r: #,encoding='utf8'
                data=eval(r.read())
        print('data:',data)
        return data


    def init_project_comb(self,data):
        """
        init project_comb items
        :param data:
        :return:
        """
        if data:
            self.project_comb.clear()
            self.project_comb.addItems(sorted(list(data.keys())))

    def init_eps_comb(self):
        """
        init eps items
        :return:
        """
        current_project=self.project_comb.currentText()
        if current_project:
            current_project_path=os.path.join(self.project_root_path,current_project)
            if os.path.exists(current_project_path):
                eps_list=os.listdir(current_project_path)
                self.eps_comb.clear()
                self.eps_comb.addItems(sorted(eps_list))
                self.current_eps=self.eps_comb.currentText()

    def init_shot_comb(self):
        """
        init shot comb items
        :return:
        """
        current_project=self.project_comb.currentText()
        current_eps=self.eps_comb.currentText()
        if current_project and current_eps:
            shot_dir=os.path.join(self.project_root_path,current_project,current_eps)
            if os.path.exists(shot_dir):
                shot_list=os.listdir(shot_dir)
                self.shot_comb.clear()
                self.shot_comb.addItems(sorted(shot_list))

    def init_pipeline_comb(self):
        """
        init pipeline items
        :return:
        """
        current_project=self.project_comb.currentText()
        current_eps=self.eps_comb.currentText()
        current_shot=self.shot_comb.currentText()

        if current_project and current_eps and current_shot:
            pipeline_dir=os.path.join(self.project_root_path,current_project,current_eps,current_shot)
            if os.path.exists(pipeline_dir):
                pipeline_list=os.listdir(pipeline_dir)
                self.pipeline_comb.clear()
                self.pipeline_comb.addItems(sorted(pipeline_list))


    def _project_changed(self,current_project):
        """
        update eps when current project changed
        :return:
        """
        self.current_project=current_project
        self.init_eps_comb()

    def _eps_changed(self,current_eps):
        self.current_eps=current_eps
        self.init_shot_comb()

    def _shot_changed(self,current_shot):
        """
        shot changed
        :param current_shot:
        :return:
        """
        self.current_shot=current_shot
        self.init_pipeline_comb()

    def _pipeline_changed(self,current_pipeline):
        """
        pipeline changed  update the shot info
        :return:
        """
        shot_info={}
        self.current_pipeline=current_pipeline
        # print(self.project_root_path,self.current_project,self.current_eps,self.current_shot,self.current_pipeline)
        shot_info_path=os.path.join(self.project_root_path,self.current_project,self.current_eps,self.current_shot,self.current_pipeline,'shot.info')

        # print('shot_info_path:',shot_info_path)
        
        if os.path.exists(shot_info_path):
            with open(shot_info_path,'r') as r:#,encoding='utf8'
                shot_info=eval(r.read())

        print("shot_info:",shot_info)
        show_text=''
        if shot_info:
            self.current_shot_info=shot_info
            project_config=self.config_data[shot_info['project']]
            fps=project_config[2]
            resolution=project_config[3]
            show_text='project:{}'.format(shot_info['project_description'])+'\n'+'FPS:{}'.format(fps)+'\n'+'resolution:{}'.format(resolution)+'\n'+'eps:{}'.format(shot_info['eps'])+'\n'+\
                      'pipeline:{}'.format(shot_info['pipeline'])+'\n'+'frame:{}'.format(shot_info['frame'])+'\n'+'artist:{}'.format(shot_info['artist'])
            self.text_brower.setText(show_text)

    def save_new_file(self,new_name):
        """
        slot from name window ,save new file
        :param new_name:
        :return:
        """
        # current_file_name=hou.hipFile.name()
        hip_path=os.path.join(self.project_root_path,self.current_project,self.current_eps,self.current_shot,self.current_pipeline)
        new_file = os.path.join(hip_path, new_name + '.hip')
        # if current_file_name=='untitled.hip':
        #     # new_file=os.path.join(hip_path,self.current_shot+'_1_version.hip')
        #     new_file = os.path.join(hip_path, new_name + '.hip')
        # else:
        #     new_file=current_file_name
        hou.hipFile.save(new_file)


    def _save_file(self):
        """
        save current hip to the path as its shot name
        :return:
        """
        new_file=''
        # current_shot_name=self.current_shot.currentText()
        self.name_window=Name()
        self.name_window.name_Signal.connect(self.save_new_file)
        self.name_window.show()

    
    def _save_update(self):
        """
        autosave file update version
        """
        new_file=''
        #current_shot_name=self.current_shot.currentText()
        current_file_name=hou.hipFile.name()
        hip_path=os.path.join(self.project_root_path,self.current_project,self.current_eps,self.current_shot,self.current_pipeline)
        if current_file_name=='untitled.hip':
            new_file=os.path.join(hip_path,self.current_shot+'_1_version.hip')
        else:
            dir_path,hip_name=os.path.split(current_file_name)
            name=os.path.splitext(hip_name)[0]
            if name.endswith('_version'):
                hip_name_list=hip_name.split('_')
                current_version=hip_name_list[-2]
                try:
                    new_version=str(int(current_version)+1)
                    hip_name_list[-2]=new_version
                    new_hip_name = '_'.join(hip_name_list)
                    new_file = os.path.join(hip_path, new_hip_name)
                except Exception as update_ERR:
                    print(update_ERR)
            else:
                new_file=os.path.join(dir_path,name+'_1_version.hip')
            
        if new_file:
            hou.hipFile.save(new_file)

    def _set_frame(self):
        """
        set the frame of current hip
        :return:
        """
        frame=self.current_shot_info['frame']
        hou.playbar.setFrameRange(1,int(frame))

    def _set_fps(self):
        """
        set current fps
        :return:
        """
        fps=self.config_data[self.current_project][2]
        hou.setFps(int(fps))


def onCreateInterface():
    widget = GlobalControl()
    return widget
if __name__ == '__main__':
    app=QApplication(sys.argv)
    #path=r'\\192.168.100.30\ZZ_project'
    path=os.path.join(os.path.dirname(os.path.dirname(__file__)),'Control')
    g=GlobalControl(path)
    g.show()
    sys.exit(app.exec_())
